<template>
  <el-dialog
      :title="form.id ? '编辑检查任务' : '添加检查任务'"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="check-task-form"
    >
      <el-form-item label="检查日期" prop="date">
        <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择检查日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :locale="zhCn"
        />
      </el-form-item>
      <el-form-item label="检查类型" prop="checkTypeId">
        <el-select v-model="form.checkTypeId" placeholder="请选择检查类型">
          <el-option
              v-for="type in checkTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检查老人" prop="elderId">
        <el-select
            v-model="form.elderId"
            placeholder="请选择或搜索老人"
            filterable
            clearable
            remote
            :remote-method="remoteSearchElder"
            :loading="searchLoading"
        >
          <el-option
              v-for="elder in filteredElderList"
              :key="elder.id"
              :label="elder.elderName"
              :value="elder.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 编辑模式下显示额外字段 -->
      <template v-if="task?.id">
        <el-form-item label="完成状态" prop="finish">
          <el-switch v-model="form.finish" @change="handleFinishChange"/>
        </el-form-item>
        <el-form-item label="是否异常" prop="hasQuestion">
          <el-switch
              v-model="form.hasQuestion"
              :disabled="!form.finish"
              :active-value="true"
              :inactive-value="false"
          />
        </el-form-item>
        <el-form-item label="检查结果" prop="result">
          <el-input
              v-model="form.result"
              type="textarea"
              :rows="4"
              placeholder="请输入检查结果"
          />
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, computed, watch, reactive, nextTick} from 'vue'
import {ElMessage} from 'element-plus'
import type {CheckTask} from '@/types/checkTask'
import type {Elder} from '@/types/elder'
import {updateDoctorCheckTask, addDoctorCheckTask} from '@/api/doctor'
import {getAllElders} from '@/api/elder'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import {CheckType} from "@/types/checkType";

const props = defineProps<{
  modelValue: boolean
  task?: CheckTask
  checkTypes: CheckType[]
  doctorId?: number
  doctorCommunityId?: number
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const formRef = ref()
const loading = ref(false)
const elderList = ref<Elder[]>([])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})
// 添加搜索相关状态
const searchLoading = ref(false)
const searchQuery = ref('')

// 计算属性过滤老人列表
const filteredElderList = computed(() => {
  if (!searchQuery.value) {
    return elderList.value
  }
  return elderList.value.filter(elder =>
      elder.elderName.includes(searchQuery.value) ||
      (elder.communityName && elder.communityName.includes(searchQuery.value))
  )
})

// 远程搜索方法
const remoteSearchElder = (query: string) => {
  searchQuery.value = query
}

const form = reactive({
  id: undefined as number | undefined,
  date: '',
  checkTypeId: undefined as number | undefined,
  childId: undefined as number | undefined,
  elderId: undefined as number | undefined,
  doctorId: undefined as number | undefined,
  finish: false,
  hasQuestion: false,
  result: ''
})

// 获取老人列表
const fetchElderList = async () => {
  try {
    const elders = await getAllElders()
    // 过滤出与医生所在社区相同的老人
    elderList.value = elders.filter(elder => elder.communityId === props.doctorCommunityId)
  } catch (error) {
    console.error('获取老人列表失败:', error)
  }
}

// 在组件挂载时获取老人列表
fetchElderList()

// 监听医生社区ID变化，重新获取老人列表
watch(() => props.doctorCommunityId, () => {
  fetchElderList()
})

const rules = {
  date: [
    {required: true, message: '请选择检查日期', trigger: 'change'}
  ],
  checkTypeId: [
    {required: true, message: '请选择检查类型', trigger: 'change'}
  ],
  elderId: [
    {required: true, message: '请选择检查老人', trigger: 'change'}
  ]
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: undefined,
    date: '',
    checkTypeId: undefined,
    childId: undefined,
    elderId: undefined,
    doctorId: undefined,
    finish: false,
    hasQuestion: false,
    result: ''
  })
}

// 1. 添加主动初始化方法
const initFormData = () => {
  if (!props.task) {
    resetForm()
    return
  }

  nextTick(() => {
    Object.assign(form, {
      id: props.task.id,
      date: props.task.date,
      checkTypeId: Number(props.task.checkTypeId || 0),
      elderId: props.task.elderId,
      finish: props.task.finish,
      hasQuestion: props.task.finish ? props.task.hasQuestion : false,
      result: props.task.result || ''
    })
  })
}

// 2. 修改监听方式（替换原有watch）
watch(() => props.modelValue, (visible) => {
  if (visible) initFormData()
}, {immediate: true})

// 3. 确保关闭时完全重置
const handleClose = () => {
  dialogVisible.value = false
  nextTick(() => {
    resetForm()
    formRef.value?.resetFields()
  })
}

// 添加完成状态变化的处理
const handleFinishChange = (isFinished: boolean) => {
  if (!isFinished) {
    form.hasQuestion = false // 未完成时强制设置为没问题
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    // 构建提交数据
    const submitData = {
      id: form.id,
      date: form.date,
      checkTypeId: form.checkTypeId,
      childId: form.childId,
      elderId: form.elderId,
      doctorId: props.doctorId
    }

    // 如果是编辑模式，添加额外字段
    if (submitData.id) {
      Object.assign(submitData, {
        finish: form.finish,
        hasQuestion: form.hasQuestion,
        result: form.result
      })
    } else {
      // 添加模式，设置默认值
      Object.assign(submitData, {
        finish: false,
        hasQuestion: false,
        result: ''
      })
    }

    if (form.id) {
      // 编辑模式
      await updateDoctorCheckTask(submitData as CheckTask)
      ElMessage.success('更新成功')
    } else {
      // 添加模式
      await addDoctorCheckTask(submitData as CheckTask)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('操作失败:', error)
  }
}
</script>


<style scoped>
.check-task-form {
  padding: 20px;
}

:deep(.el-switch.is-disabled) {
  opacity: 0.6;
  cursor: not-allowed;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper),
:deep(.el-textarea__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover),
:deep(.el-textarea__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus),
:deep(.el-textarea__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 